package com.wuliupai.delivery.wuliupaidelivery.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.RxBus;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;
    private TextView tv_payResultTips;
    private Button btn_rePay;
    private ImageView iv_resultIcon;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_result);
        btn_rePay = (Button) findViewById(R.id.btn_rePay);
        tv_payResultTips = (TextView) findViewById(R.id.tv_payResultTips);
        iv_resultIcon = (ImageView) findViewById(R.id.iv_resultIcon);

        btn_rePay.setOnClickListener(arg0 -> {
            RxBus.get().post(BroadcastChannels.Channel_Repay, "");
            finish();
        });

        findViewById(R.id.btn_cancel).setOnClickListener(v -> finish());

        api = WXAPIFactory.createWXAPI(this, Value.WEIXIN_APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        LogUtils.log("微信支付结果---Code:" +
                resp.errCode + "\nStr:" +
                resp.errStr + "\nopenId:" +
                resp.openId + "\ntransaction:" +
                resp.transaction + "\ntoString():" +
                resp.toString());
        if (resp.errCode == 0) {
            //支付成功
            iv_resultIcon.setImageResource(R.mipmap.happy);
            tv_payResultTips.setText(R.string.string_payFee_weChat_payResultSuccessful);
            RxBus.get().post(BroadcastChannels.Channel_WeChatPaySuccessfully, "");
        } else if (-2 == resp.errCode) {
            btn_rePay.setVisibility(View.VISIBLE);
            tv_payResultTips.setText(R.string.string_payFee_weChat_payResultCancel);
        } else {
            btn_rePay.setVisibility(View.VISIBLE);
            tv_payResultTips.setText(R.string.string_payFee_weChat_payResultErr);
        }
    }
}